<template>
  <base-load-page :loadState="false" class="base-load-page">
    <template #head>
      <div style="padding-bottom: 15px" class="head-box">
        <div class="left-box">
          <base-input-search
            v-model="filterData.dramaTitle"
            clearable
            placeholder="请输入短剧名称"
            style="width: 100%"
            :prefixIcon="IconSearch"
            @submit="getAxiosData(true)"
          ></base-input-search>
          <bubble-select-local
            v-model="filterData.dramaStatus"
            labelKey="label"
            valueKey="value"
            :filterable="false"
            style="width: 100%"
            :list="[
              { label: '全部', value: '' },
              { label: '未上映', value: 1 },
              { label: '更新中', value: 2 },
              { label: '已完结', value: 3 },
            ]"
            placeholder="请选择更新状态"
            @change="getAxiosData(true)"
          ></bubble-select-local>
          <bubble-select-local
            v-model="filterData.categoryId"
            labelKey="categoryName"
            valueKey="categoryId"
            style="width: 100%"
            :param="{ haveAll: true }"
            :axios="dramaCategoryListAxios"
            placeholder="请选择分类"
            @change="getAxiosData(true)"
          ></bubble-select-local>
        </div>
        <div class="right-box">
          <el-button type="success" :icon="IconSolarVideocameraAddOutline" @click="handleAddDrama()">新增</el-button>
        </div>
      </div>
    </template>
    <el-table ref="elTableRef" v-loading="baseData.loading" border height="100%" :data="tableData" showOverflowTooltip stripe style="width: 100%">
      <template #empty>
        <base-empty :description="description" :pageLoadButton="[{ text: '重新加载', callBack: () => getAxiosData() }]"></base-empty>
      </template>
      <el-table-column
        fixed
        type="index"
        :index="(index: number) => (filterData.current - 1) * filterData.size + index + 1"
        label="编号"
        sortable
        width="60"
        align="center"
        headerAlign="center"
      ></el-table-column>
      <el-table-column fixed label="海报" prop="dramaTitle" minWidth="72">
        <template #default="{ row }">
          <base-image
            style="width: 45px; height: 80px; border-radius: 4px"
            :src="row.dramaCover"
            previewTeleported
            :previewSrcList="[row.dramaCover!]"
          ></base-image>
        </template>
      </el-table-column>
      <el-table-column fixed label="短剧名称" prop="dramaTitle" minWidth="180">
        <template #default="{ row }">
          <el-link @click="toDramaDesc(row)">{{ row.dramaTitle }}</el-link>
        </template>
      </el-table-column>
      <el-table-column label="短剧ID" prop="dramaId" minWidth="140"></el-table-column>
      <el-table-column label="上映状态" width="90">
        <template #default="{ row }">
          <el-tag :type="row.dramaStatus === 3 ? 'success' : row.dramaStatus === 2 ? 'primary' : 'info'" size="small">{{ row.dramaStatusDesc }}</el-tag>
        </template>
      </el-table-column>
      <el-table-column label="整剧免费" width="90">
        <template #default="{ row }">
          <el-tag v-if="row.isFree === 1" key="el-tag-1" type="success" size="small">是</el-tag>
          <el-tag v-else key="el-tag-2" type="danger" size="small">否</el-tag>
        </template>
      </el-table-column>
      <el-table-column label="总集数" prop="seqNum" minWidth="90"></el-table-column>
      <el-table-column label="分享解锁集数" prop="shareUnlockNum" width="120"></el-table-column>
      <el-table-column label="免费集数" prop="freeEpisodeNum" minWidth="90"></el-table-column>
      <el-table-column label="单集价格" prop="price" sortable minWidth="110"></el-table-column>
      <el-table-column label="单集K币" prop="virtualCoin" sortable minWidth="110"></el-table-column>
      <el-table-column label="全集价格" prop="allEpisodePrice" sortable minWidth="110"></el-table-column>
      <el-table-column label="全集K币" prop="allEpisodeVirtualCoin" sortable minWidth="110"></el-table-column>
      <el-table-column label="分类" prop="dramaCategoryName" minWidth="120"></el-table-column>
      <el-table-column label="导演" prop="director" minWidth="90"></el-table-column>
      <el-table-column label="演员" prop="performer" minWidth="90"></el-table-column>
      <el-table-column label="标签" prop="tags" minWidth="120"></el-table-column>
      <el-table-column label="推荐状态" fixed="right" width="90" align="center" headerAlign="center">
        <template #default="{ row }">
          <div style="display: flex; flex-direction: column">
            <el-switch
              v-model="row.isRecommend"
              style="--el-switch-on-color: var(--el-color-success); --el-switch-off-color: var(--el-color-danger)"
              inlinePrompt
              activeText="已推荐"
              inactiveText="未推荐"
              :activeValue="1"
              :inactiveValue="0"
              :loading="row._isRecommendLoading"
              :beforeChange="() => handleSetIsRecommendSingle(row)"
            ></el-switch>
          </div>
        </template>
      </el-table-column>
      <el-table-column label="上架状态" fixed="right" width="180" align="center" headerAlign="center">
        <template #default="{ row }">
          <div style="display: grid; grid-template-columns: repeat(2, 1fr); align-items: center">
            <el-switch
              v-model="row.dyStatus"
              style="--el-switch-on-color: var(--el-color-success); --el-switch-off-color: var(--el-color-danger)"
              inlinePrompt
              activeText="抖音上架"
              inactiveText="抖音下架"
              :activeValue="1"
              :inactiveValue="0"
              :loading="row._statusLoading"
              :beforeChange="() => handleSetStateSingle(row, 'mp-toutiao')"
            ></el-switch>
            <el-switch
              v-model="row.wechatStatus"
              style="--el-switch-on-color: var(--el-color-success); --el-switch-off-color: var(--el-color-danger)"
              inlinePrompt
              activeText="微信上架"
              inactiveText="微信下架"
              :activeValue="1"
              :inactiveValue="0"
              :loading="row._statusWxLoading"
              :beforeChange="() => handleSetStateSingle(row, 'mp-weixin')"
            ></el-switch>
            <el-switch
              v-model="row.ksStatus"
              style="--el-switch-on-color: var(--el-color-success); --el-switch-off-color: var(--el-color-danger)"
              inlinePrompt
              activeText="快手上架"
              inactiveText="快手下架"
              :activeValue="1"
              :inactiveValue="0"
              :loading="row._statusKsLoading"
              :beforeChange="() => handleSetStateSingle(row, 'mp-kuaishou')"
            ></el-switch>
          </div>
          <div style="display: grid; grid-template-columns: repeat(2, 1fr); align-items: center">
            <el-switch
              v-model="row.webStatus"
              style="--el-switch-on-color: var(--el-color-success); --el-switch-off-color: var(--el-color-danger)"
              inlinePrompt
              activeText="WEB上架"
              inactiveText="WEB下架"
              :activeValue="1"
              :inactiveValue="0"
              :loading="row._statusWebLoading"
              :beforeChange="() => handleSetStateSingle(row, 'web')"
            ></el-switch>
            <el-switch
              v-model="row.appStatus"
              style="--el-switch-on-color: var(--el-color-success); --el-switch-off-color: var(--el-color-danger)"
              inlinePrompt
              activeText="APP上架"
              inactiveText="APP下架"
              :activeValue="1"
              :inactiveValue="0"
              :loading="row._statusAppLoading"
              :beforeChange="() => handleSetStateSingle(row, 'app')"
            ></el-switch>
          </div>
        </template>
      </el-table-column>
      <el-table-column fixed="right" label="操作" width="100" align="center" headerAlign="center">
        <template #default="{ row }">
          <div style="display: flex; flex-direction: column; gap: 6px; overflow: hidden">
            <el-button link type="danger" size="small" style="margin-left: 0" :icon="IconDelete" @click="handleDel([row])">删除短剧</el-button>
            <el-button link type="primary" size="small" style="margin-left: 0" :icon="IconEdit" @click="openEditDrama(row.dramaId)">编辑短剧</el-button>
            <el-button link type="warning" size="small" style="margin-left: 0" :icon="IconSolarListLinear" @click="handleEpisodeList(row)">剧集列表</el-button>
            <el-button link type="info" size="small" style="margin-left: 0" :icon="IconSolarListLinear" @click="handleTencentList(row)">腾讯类目</el-button>
          </div>
        </template>
      </el-table-column>
    </el-table>
    <template #foot>
      <div class="pagination-box">
        <el-pagination
          v-model:currentPage="filterData.current"
          v-model:pageSize="filterData.size"
          :pageSizes="[20, 30, 40, 50]"
          :disabled="baseData.loading"
          :pagerCount="13"
          layout="total, prev, pager, next, sizes, jumper"
          :total="baseData.total"
          @change="getAxiosData(true)"
        ></el-pagination>
      </div>
    </template>
    <add-episode ref="addEpisodeRef"></add-episode>
    <episode-list ref="episodeListRef"></episode-list>
    <tencent-category ref="tencentCategoryRef"></tencent-category>
  </base-load-page>
</template>

<script setup lang="ts">
  import IconSearch from '~icons/ep/search';
  import IconDelete from '~icons/ep/delete';
  import IconEdit from '~icons/ep/edit';
  import { Session } from '@/utils/storage.ts';
  import { $mitt, UPDATE_DRAMA_LIST_MITT } from '@/utils/mitt-event';
  import IconSolarListLinear from '~icons/solar/list-linear';

  import IconSolarVideocameraAddOutline from '~icons/solar/videocamera-add-outline';
  import {
    type DamaListRequest,
    type DramaItem,
    changeIsRecommendAxios,
    changesStatusAxios,
    delDamaAxios,
    dramaCategoryListAxios,
    getDamaListAxios,
  } from '@/api/drama-management';
  import EpisodeList from './components/episode-list.vue';
  import AddEpisode from './components/add-episode.vue';
  import TencentCategory from './components/tencent-category.vue';

  type _DramaItem = DramaItem & {
    /** 修改冻结状态的加载状态 */
    _allStatusLoading?: boolean;
    _statusLoading?: boolean;
    _statusWxLoading?: boolean;
    _statusKsLoading?: boolean;
    _statusAppLoading?: boolean;
    _statusWebLoading?: boolean;
    /** 修改冻结状态的加载状态 */
    _isRecommendLoading?: boolean;
    /** 修改抖音推送的加载状态 */
    _publishDyLoading?: boolean;
    /** 修改快手推送的加载状态 */
    _publishKsLoading?: boolean;
  };
  onMounted(() => {
    getAxiosData();
    $mitt.on(UPDATE_DRAMA_LIST_MITT, () => {
      getAxiosData();
    });
  });
  onUnmounted(() => {
    $mitt.off(UPDATE_DRAMA_LIST_MITT);
  });

  const router = useRouter();
  const elTableRef: $RefComp<'ElTable'> = ref(null);
  const episodeListRef: $RefComp<typeof EpisodeList> = ref(null);
  const addEpisodeRef: $RefComp<typeof AddEpisode> = ref(null);
  const tencentCategoryRef: $RefComp<typeof TencentCategory> = ref(null);
  const baseData = shallowReactive({
    type: 'add' as 'add' | 'edit',
    /** 加载状态 */
    loading: true,
    /** 总数量 */
    total: 0,
  });
  const filterData: Ref<DamaListRequest> = ref<DamaListRequest>({
    dramaTitle: '',
    categoryId: '',
    status: '',
    dramaStatus: '',
    current: 1,
    size: 40,
  });

  const tableData: Ref<_DramaItem[]> = ref([]);
  const description = ref('');
  /**
   * 设置表格数据
   */
  async function getAxiosData(showLoading = true) {
    try {
      await nextTick();
      baseData.loading = Boolean(showLoading);
      const res = await getDamaListAxios(filterData.value);
      tableData.value = res.data.records;
      description.value = '暂无数据';
      filterData.value.current = res.data.current;
      filterData.value.size = res.data.size;
      baseData.total = res.data.total;
      baseData.loading = false;
    } catch (error) {
      baseData.loading = false;
      tableData.value = [];
      description.value = error.msg || '加载失败，-BD001';
    }
  }

  /** 编辑编辑短剧信息*/
  function openEditDrama(dramaId: number) {
    router.push(`/drama-management/drama-info?type=edit&dramaId=${dramaId}`);
  }

  /** 新增短剧 */
  function handleAddDrama() {
    router.push('/drama-management/drama-info?type=add');
  }

  /** 新增剧集 */
  function handleEpisodeList(row: _DramaItem) {
    episodeListRef.value?.show({ dramaId: row.dramaId!, dramaTitle: row.dramaTitle! });
  }

  /** 腾讯类目 */
  function handleTencentList(row: _DramaItem) {
    tencentCategoryRef.value?.show({ dramaId: row.dramaId });
  }

  /** 删除短剧 */
  function handleDel(row: _DramaItem[]) {
    if (row.length > 0) {
      ElMessageBox.confirm('删除后不可恢复，您确定删除吗？', '温馨提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
        draggable: true,
        beforeClose: async (action, instance, done) => {
          if (action === 'confirm') {
            instance.confirmButtonLoading = true;

            const ids = row.map((item) => item.dramaId!);
            try {
              await delDamaAxios(ids);
              await getAxiosData(false);
              ElToast.success('删除成功');
            } catch (error) {
              ElToast.error(error.msg || '删除失败，-BD004');
            }
          }
          done();
        },
      });
    } else {
      ElToast.warning('请选择需要删除的短剧');
    }
  }

  type PlatformFlag = 'app' | 'mp-kuaishou' | 'mp-toutiao' | 'mp-weixin' | 'web';
  const statusMap: Record<string, keyof DramaItem> = {
    'app': 'appStatus',
    'mp-kuaishou': 'ksStatus',
    'mp-toutiao': 'dyStatus',
    'mp-weixin': 'wechatStatus',
    'web': 'webStatus',
  };
  /** 修改单个平台上架状态 */
  async function handleSetStateSingle(row: _DramaItem, flag: PlatformFlag): Promise<boolean> {
    const name = row[statusMap[flag]!] === 1 ? '下架' : '上架';
    try {
      changeArrivalLoadingStatus(row, flag, true);
      await changesStatusAxios(row.dramaId!, row[statusMap[flag]!] === 1 ? 0 : 1, flag);
      changeArrivalLoadingStatus(row, flag, false);
      ElToast.success(`${name}成功`);
      return Promise.resolve(true);
    } catch (error) {
      changeArrivalLoadingStatus(row, flag, false);

      ElToast.error(error.msg || `${name}失败，-BD004`);
      return Promise.reject(false);
    }
  }

  /** 修改推荐状态 */
  async function handleSetIsRecommendSingle(row: _DramaItem): Promise<boolean> {
    const name = row.isRecommend === 1 ? '取消推荐' : '推荐';
    try {
      row._isRecommendLoading = true;
      await changeIsRecommendAxios(row.dramaId!);
      row._isRecommendLoading = false;
      ElToast.success(`${name}成功`);
      return Promise.resolve(true);
    } catch (error) {
      row._isRecommendLoading = false;
      ElToast.error(error.msg || `设置${name}失败，-BD004`);
      return Promise.reject(false);
    }
  }

  /** 修改loading */
  function changeArrivalLoadingStatus(originRow: _DramaItem, flag: PlatformFlag, state: boolean) {
    switch (flag) {
      case 'app':
        originRow._statusAppLoading = state;
        break;
      case 'mp-toutiao':
        originRow._statusLoading = state;
        break;
      case 'mp-kuaishou':
        originRow._statusKsLoading = state;
        break;
      case 'web':
        originRow._statusWebLoading = state;
        break;
      case 'mp-weixin':
        originRow._statusWxLoading = state;
        break;

      default:
        break;
    }
  }

  /**
   * 剧集详情页
   */
  function toDramaDesc(row: _DramaItem) {
    Session.set(`dramaPreview_${row.dramaId}`, row);
    router.push(`/drama-management/drama-preview?dramaId=${row.dramaId}`);
  }
</script>

<style lang="scss" scoped>
  .pagination-box {
    @include flex(row, nowrap, center, center, center);
    padding-top: 15px;
  }

  .head-box {
    @include flex(row, nowrap, flex-start, center, center);

    .left-box {
      display: grid;
      flex: 1;
      grid-template-columns: repeat(auto-fill, minmax(190px, 1fr));
      grid-gap: 15px;
      margin-right: 15px;
    }
  }
</style>
